use std::collections::{HashMap, HashSet};
use std::fs;

pub fn count_provinces() -> String {
    let content = fs::read_to_string("district.json").expect("Failed to read file");

    let mut results = Vec::new();
    let mut cities = HashSet::new();
    let mut in_quotes = false;
    let mut current_city = String::new();
    let mut depth = 0;

    for c in content.chars() {
        match c {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 1 {
                    // End of a batch
                    let province_count = count_provinces_for_cities(&cities);
                    if province_count > 0 {
                        results.push(province_count.to_string());
                    }
                    cities.clear();
                }
            }
            '"' => {
                if depth >= 2 {
                    // Inside a batch
                    if in_quotes {
                        if !current_city.is_empty() {
                            cities.insert(current_city.clone());
                            current_city.clear();
                        }
                    }
                    in_quotes = !in_quotes;
                }
            }
            _ => {
                if in_quotes {
                    current_city.push(c);
                }
            }
        }
    }

    results.join(",")
}

fn count_provinces_for_cities(cities: &HashSet<String>) -> usize {
    let province_map = create_province_map();
    let mut provinces = HashSet::new();

    for city in cities {
        if let Some(&province) = province_map.get(city.as_str()) {
            provinces.insert(province);
        }
    }

    provinces.len()
}

fn create_province_map() -> HashMap<&'static str, &'static str> {
    let mut map = HashMap::new();
    let content = fs::read_to_string("src/pc.json").expect("Failed to read file");

    let mut in_quotes = false;
    let mut current_text = String::new();
    let mut province = String::new();
    let mut is_province = true;

    for c in content.chars() {
        match c {
            '"' => {
                if in_quotes {
                    let text = current_text.trim();
                    if !text.is_empty() {
                        if is_province {
                            province = remove_suffix(text.to_string());
                            is_province = false;
                        } else {
                            let city = remove_suffix(text.to_string());
                            let static_city: &'static str = Box::leak(city.into_boxed_str());
                            let static_province: &'static str =
                                Box::leak(province.clone().into_boxed_str());
                            map.insert(static_city, static_province);
                        }
                    }
                    current_text.clear();
                }
                in_quotes = !in_quotes;
            }
            '[' => is_province = false,
            ']' => is_province = true,
            _ => {
                if in_quotes {
                    current_text.push(c);
                }
            }
        }
    }
    map
}

fn remove_suffix(text: String) -> String {
    let suffixes = [
        "市",
        "区",
        "自治区",
        "自治州",
        "林区",
        "地区",
        "特别行政区",
        "土家族苗族自治州",
        "回族自治州",
        "维吾尔自治区",
        "壮族自治区",
        "藏族自治州",
        "蒙古自治州",
        "蒙古族藏族自治州",
        "傣族自治州",
        "彝族自治州",
        "白族自治州",
        "哈尼族彝族自治州",
        "县",
        "自治县",
        "盟",
        "城区",
        "堂区",
    ];

    for suffix in suffixes.iter() {
        if text.ends_with(suffix) {
            return text[..text.len() - suffix.len()].to_string();
        }
    }
    text
}
